package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 8/25/13
 * Time: 11:07 AM
 * To change this template use File | Settings | File Templates.
 */
public class Security {
    private PrintStream printSream;
    private BufferedReader bufferedReader;
    private HashMap<String, User> users;
    private static int libraryNumberCounter;
    private static User loggedUser;


    public Security(HashMap<String, User> users) {
        this();
        this.users = users;
    }

    public Security() {
        this.users = new HashMap<String, User>();
        this.libraryNumberCounter = 1111111;

    }

    public Security(BufferedReader bufferedReader, PrintStream printStream) {
        this();
        this.bufferedReader = bufferedReader;
        this.printSream = printStream;
    }

    public Security(BufferedReader bufferedReader, PrintStream printStream, HashMap<String, User> users) {
        this.bufferedReader = bufferedReader;
        this.printSream = printStream;
        this.users = users;
    }

    public User getUserByUsername(String username) {
        return users.get(username);
    }

    public void createNewUser(String username, String password) {
        if (users == null)
            users = new HashMap<String, User>();
        User user = new User(username, password);
        user.setLibraryNumber(libraryNumberCounter);
        users.put(username, user);
        libraryNumberCounter++;
    }

    public boolean loginUser(String username, String password) {
        User user = getUserByUsername(username);

        boolean isValidLogIn = (user != null && user.getPassword().equals(password));
        if (isValidLogIn)
            loggedUser = user;

        return isValidLogIn;
    }

    public User getLoggedUser() {
        return loggedUser;
    }

    public boolean promptForCredentials() {
        boolean result;
        try {
            printSream.println("Username:");
            String username = bufferedReader.readLine();
            printSream.println("Password:");
            String password = bufferedReader.readLine();
            result = loginUser(username, password);
        } catch (IOException e) {
            result = false;
        }
        return result;
    }
}
